package com.ymatou.shop.ui.activity.buyer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.Address;
import com.ymatou.shop.model.LoginResult;
import com.ymatou.shop.model.Order;
import com.ymatou.shop.model.Product;
import com.ymatou.shop.model.ResponseMessage;
import com.ymatou.shop.ui.activity.BaseHeaderActivity;
import com.ymatou.shop.util.GlobalUtil;
import com.ymatou.shop.util.StringUtil;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class SaveOrderActivity extends BaseHeaderActivity implements OnClickListener {

	private static final int REQUEST_ID_GET_USER_ADDRESS = 0;
	private static final int REQUEST_ID_GET_USER_ACCOUNT_INFO = 1;
	private static final int REQUEST_ID_SAVE_ORDER = 2;
	private static final int REQUEST_CODE = 1;
	public final static String BITMAPS_KEY = "bitmpas";
	public final static String PRODUCT_KEY = "product";
	private TextView redMoneyTextView, userAddressTextView, productDesTextView, priceTextView, depositTextView, leavewordTextView;
	private EditText redMoneyTextView2;
	private View addressLayout;
	private ImageView userHeaderImageView;
	private Product mProduct;
	private List<Address> mAddressList;
	private LoginResult mLoginResult;
	private Address mCurrentAddress;
	private String leaveword, userGiftAmout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.save_order);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		getIntentData();
		setupViews();
		setData();
	}

	private void getIntentData() {
		if (getIntent() != null) {
			mProduct = (Product) getIntent().getSerializableExtra(PRODUCT_KEY);
		}
	}

	
	private void getUserAddress() {
		RequestInfo requestInfo = ApiRequest.getUserAddress();
		getCacheManager().register(REQUEST_ID_GET_USER_ADDRESS, requestInfo, this);
	}

	private void saveOrder() {
		RequestInfo requestInfo = ApiRequest.saveOrder(mProduct.mId, "1", 
				mCurrentAddress.mAddressId, leaveword, userGiftAmout);
		getCacheManager().register(REQUEST_ID_SAVE_ORDER, requestInfo, this);
	}

	private void setData() {
		getUserAccountInfo();
		getUserAddress();
	}

	@Override
	protected void setupViews() {
		super.setupViews();

		getTitleLeftImageButton().setImageResource(R.drawable.back_icon);
		getTitleLeftImageButton().setOnClickListener(this);
		getTitleLeftImageButton().setVisibility(View.VISIBLE);
		getTitleLeftImageButton().setBackgroundDrawable(null);
		getTitleTextView().setText(R.string.product_pay_cash);

		addressLayout = findViewById(R.id.address_layout);
		addressLayout.setOnClickListener(this);
		userAddressTextView = (TextView) findViewById(R.id.user_address_textview);
		userHeaderImageView = (ImageView) findViewById(R.id.user_head_imageview);
		Drawable drawable = ImageCache.get(this, mProduct.mImageList[0], new ImageCache.OnIconLoadCompleteListener() {
			@Override
			public void onLoadComplete(String url, boolean success, Drawable drawable) {
				if (success) {
					userHeaderImageView.setImageDrawable(drawable);
				}
			}
		});
		if (drawable != null) {
			userHeaderImageView.setImageDrawable(drawable);
		}

		productDesTextView = (TextView) findViewById(R.id.product_description);
		productDesTextView.setText(mProduct.mDescription);

		priceTextView = (TextView) findViewById(R.id.price);
		priceTextView.setText(getString(R.string.red_money_textview2, mProduct.mPrice));
		depositTextView = (TextView) findViewById(R.id.deposit);
		depositTextView.setText(getString(R.string.red_money_textview2, mProduct.mDownPayment));

		redMoneyTextView = (TextView) findViewById(R.id.red_money);
		redMoneyTextView2 = (EditText) findViewById(R.id.red_money2);

		redMoneyTextView2.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				GlobalUtil.logE(v.getText().toString());
				return false;
			}
		});
		
		leavewordTextView = (TextView)findViewById(R.id.leaveword);
		
		findViewById(R.id.ok_textview).setOnClickListener(this);

		
		
	}

	private void getUserAccountInfo() {
		RequestInfo request3 = ApiRequest.getAccountInfo();
		getCacheManager().register(REQUEST_ID_GET_USER_ACCOUNT_INFO, request3, this);
	}

	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo, Object response) {
		cancelProgressDialog();
		switch (requestId) {
		case REQUEST_ID_GET_USER_ADDRESS:
			mAddressList = ApiResponse.getUserAddressList((String) response);
			if (mAddressList != null && mAddressList.size() > 0) {
				mCurrentAddress = mAddressList.get(0);
				userAddressTextView.setText(mCurrentAddress.mArea + mCurrentAddress.mDetailAddress);
			} else {
				userAddressTextView.setText("无");
			}
			break;
		case REQUEST_ID_GET_USER_ACCOUNT_INFO:
			mLoginResult = ApiResponse.getAccountInfo((String) response);
			redMoneyTextView.setText(getString(R.string.red_money_textview, mLoginResult.mGiftAvailAmount));
			break;
		case REQUEST_ID_SAVE_ORDER:
			ResponseMessage mResponseMessage = ApiResponse.saveOrder((String) response);
			if (mResponseMessage.status == 200){
				if (StringUtil.isNotEmpty(mResponseMessage.payUrl)){
					GlobalUtil.shortToast(this, mResponseMessage.payUrl);
				}else {
					GlobalUtil.shortToast(this, mResponseMessage.message);	
				}
				
			}
			
			
			
			break;
		default:

			break;
		}
		super.onCacheSuccess(requestId, requestInfo, response);
	}

	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo, CacheException error) {
		super.onCacheFailed(requestId, requestInfo, error);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.address_layout:
			Intent intent = new Intent(v.getContext(), AddressActivity.class);
			intent.putExtra(AddressActivity.ADDRESS_KEY, (Serializable) mAddressList);
			
			GlobalUtil.startActivityForResult(SaveOrderActivity.this, intent, REQUEST_CODE);
			break;

		case R.id.ok_textview:
			leaveword = leavewordTextView.getText().toString();
			userGiftAmout = redMoneyTextView2.getText().toString();
			if (StringUtil.isEmpty(userGiftAmout)){
				userGiftAmout = "0";
			}
			saveOrder();
			
			GlobalUtil.startPayOrderActivity(v.getContext(), mProduct, mLoginResult, Float.parseFloat(userGiftAmout));
			finish();
			
			break;


		case R.id.title_left_image_button:
				onBackPressed();

			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
			mAddressList = (ArrayList<Address>)data.getSerializableExtra(AddressActivity.ADDRESS_KEY);
			if (mAddressList != null && mAddressList.size() > 0) {
				mCurrentAddress = mAddressList.get(0);
//				GlobalUtil.shortToast(getApplicationContext(), "mCurrentAddress.mAddressId " + mCurrentAddress.mAddressId);
				userAddressTextView.setText(mCurrentAddress.mArea + mCurrentAddress.mDetailAddress);
			} else {
				userAddressTextView.setText("无");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
